#include "client.h"
#include "server.h"
#include "log.h"
#include "graphics.h"

#include <SDL/SDL.h>
#include <SDL/SDL_thread.h> 
//errorlog_t* lg = new errorlog_t();
// or
errorlog_t* lg = new errorlog_t("!log.txt");


// SDL threads
// server thread
int net_server_thread(void *data) {
    Server * s = reinterpret_cast<Server*> (data);
    s->main_server_thread();
    return 0;    
};
// client thread
int net_client_thread(void *data) {
    Client * s = reinterpret_cast<Client*> (data);
    s->main_client_thread();
    return 0;    
};
// 
int test_thread(void *data) {
    Graphics * g = reinterpret_cast<Graphics*> (data);
    g->main();
    return 0;    
};


int main(int argc, char **argv) { 
  *lg << string(40,'-') << fl << debug << "Start of session" << fl;
  
  #if defined(WIN32) 
   *lg << debug << "Running on Windoze enviroment" << fl;
  #else
	#if defined(linux)
		*lg << debug << "Running on LINUX env" << fl;
	#else
   		*lg << debug << "Running on unknown enviroment" << fl;
	#endif
  #endif
  
  
  // bshit
  *lg << info << "yeah yeah" << '!' << fl;
  *lg << critical << "hups" << nl << 56 << fl;
  
  
  // init server thread
  Server* Srv = new Server();
  if(Srv->initserver(6661)==0) *lg << info << "Server started" << fl;
    
  SDL_Thread *server_thread;
  server_thread=SDL_CreateThread(net_server_thread,  reinterpret_cast<void*>(Srv));
  if(!server_thread) {
		  *lg << error << "SDL_CreateThread: " << SDL_GetError() << fl;
  } else {
      *lg << info << "Server thread created" << fl;
  }
  
  // init client thread
  Client *client = new Client();
  
  SDL_Thread *client_thread;
  client_thread=SDL_CreateThread(net_client_thread,  reinterpret_cast<void*>(client));
  if(!client_thread) {
		  *lg << error << "SDL_CreateThread: " << SDL_GetError() << fl;
  } else {
      *lg << info << "Client thread created" << fl;
  }

  // init graphics thread
  SDL_Thread *g_thread;
  Graphics* g = new Graphics();

  g->init(client);

  g_thread = SDL_CreateThread(test_thread, reinterpret_cast<void*>(g)); 

  // wait for all threads to finish
  SDL_WaitThread(g_thread,NULL);
	delete g;
  SDL_WaitThread(server_thread,NULL);   
  SDL_WaitThread(client_thread,NULL);   

	
	*lg << debug << "The very end" << fl;
	return 0;
};

